package com.qf.chat.controller;


import com.qf.chat.commons.base.BaseController;
import com.qf.chat.commons.r.Codes;
import com.qf.chat.commons.r.R;
import com.qf.chat.commons.utils.CodesUtils;
import com.qf.chat.commons.utils.JwtUtils;
import com.qf.chat.entity.User;
import com.qf.chat.entity.vo.UserLoginVo;
import com.qf.chat.entity.vo.UserUpdatePasswordVo;
import com.qf.chat.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * 用户表(User)表控制层
 *
 * @author makejava
 * @since 2024-01-12 10:47:52
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController extends BaseController<UserService> {
    
    @PostMapping("/register")
    public R register(@RequestBody @Validated User user) {
        log.debug("[user register] 用户注册 - {}", user);
        return R.succ(getBaseService().save(user));
    }

    @PostMapping("/login")
    public R login(@RequestBody UserLoginVo userLoginVo){
        log.debug("[user login] 用户登录 - {}", userLoginVo);

        //查询用户信息
        User user = getBaseService().queryUserByUsernameAndPassword(userLoginVo);
        if (user == null) {
            return R.fail(Codes.LOGIN_FAIL);
        }

        //将用户信息 - user对象 -> 转换成Jwt令牌，返回给客户端
        String jwtToken = JwtUtils.createJwtToken()
                .add("id", user.getId())
                .add("nickname", user.getNickname())
                .add("header", user.getHeader())
                .build();

        return R.succ(jwtToken);
    }

    /**
     * 修改密码
     * @return
     */
    @PostMapping("/updatePassword")
    public R updatePassword(@RequestBody @Validated UserUpdatePasswordVo userUpdatePasswordVo){
        log.debug("修改用户密码 - {}", userUpdatePasswordVo);

        //判断验证码
        int inputCode = userUpdatePasswordVo.getCode();
        //生成验证码 - 5分钟的时效性
        Integer createCode = CodesUtils.getCode(userUpdatePasswordVo.getUsername());

        if (!Objects.equals(createCode, inputCode)) {
            //验证码不匹配
            return R.fail(Codes.CODE_ERROR);
        }

        //修改密码
        getBaseService().updateUserPassword(userUpdatePasswordVo.getUsername(), userUpdatePasswordVo.getPassword());

        //删除验证码
        CodesUtils.remove(userUpdatePasswordVo.getUsername());

        return R.succ();
    }

    /**
     * 根据关键词搜索
     * @return
     */
    @GetMapping({"/search/{keyword}", "/search/"})
    public R search(@PathVariable(required = false) String keyword){
        log.debug("根据关键词搜索 - {}", keyword);
        return R.succ(getBaseService().searchUserByKeyword(keyword));
    }
}

